package com.fast.develop.meta.base.resource;


import com.fast.develop.meta.base.util.FileUtil;
import com.fast.develop.meta.base.util.PathFilter;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/**
 * @author 莫寅
 * @createTime 2022-06-25 00:22
 * @desc：
 */
public class MetaFileMultResource implements MultResource<PathResource> {

    private List<PathResource> resourceList;
    private String path;

    public MetaFileMultResource(String path){
        this.path = path;
        readResource(path);
    }

    public MetaFileMultResource (String path, PathFilter pathFilter){
        readResource(path, pathFilter);
        this.path = path;
    }

    private void readResource(String path){
        Map<String, InputStream> pathInputStream = FileUtil.loopFiles(path, new PathFilter() {
            @Override
            public boolean accept(String path) {
                if(cn.hutool.core.io.FileUtil.getSuffix(path).equals("json")){
                    return true;
                }
                return false;
            }
        });

        List<PathResource> resources = pathInputStream.entrySet().stream().map(entry -> {
            return new PathResource(entry.getKey(), entry.getValue());
        }).collect(Collectors.toList());

        this.resourceList = resources;
    }

    private void readResource(String path, PathFilter pathFilter){
        Map<String, InputStream> files = FileUtil.loopFiles(path, pathFilter);

        List<PathResource> resources = files.entrySet().stream().map(entry -> {
            return new PathResource(entry.getKey(), entry.getValue());
        }).collect(Collectors.toList());

        this.resourceList = resources;
    }

    @Override
    public Iterator<PathResource> iterator() {
        return Collections.unmodifiableList(this.resourceList).iterator();
    }

    @Override
    public Stream<PathResource> stream() {
        return StreamSupport.stream(spliterator(), false);
    }


    @Override
    public Spliterator<PathResource> spliterator() {
        return Spliterators.spliterator(getResources(), 0);
    }


    @Override
    public PathResource[] getResources(){
        return this.resourceList.toArray(new PathResource[0]);
    }

    @Override
    public List<InputStream> getInputStreams() {
        return this.resourceList.stream().map(PathResource::getInputStream).collect(Collectors.toList());
    }

    @Override
    public void reload() {
        readResource(path);
    }

    public String getPath() {
        return path;
    }
}
